package com.itheima.reggie.handler;


import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.core.DuplicatesPredicate;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局异常处理
@RestControllerAdvice       //ResponseBody + ControllerAdvice
@Slf4j      //日志
public class GlobalExceptionHandler {

    //unique设置
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultInfo duplicationHandler(Exception ex){
        //1. 记录错误信息
        log.error(ex.getMessage());
        //2. 返回错误信息
        return ResultInfo.error("添加失败:分类名重复");
    }

    //预期异常
    @ExceptionHandler(CustomException.class)        //添加自定义异常类
    public ResultInfo customExceptionHandler(CustomException ex){
        //1.记录错误信息
        log.error(ex.getMessage());
        //2.返回错误信息
        return ResultInfo.error(ex.getMessage());
    }

    //非预期异常     ==>     兜底
    @ExceptionHandler(Exception.class)
    public ResultInfo exceptionHandler(Exception ex){
        //1.记录错误信息
        log.error(ex.getMessage());
        //2.返回错误信息
        return ResultInfo.error("服务器繁忙,请稍后重试");
    }

}
